<template>
  <div class="subjects-add">
    <div class="header">
      <!-- 学科名称搜索框 -->
      <el-form
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
        :model="subjectsForm"
        ref="subjectsForm"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            placeholder="请输入学科名称"
            v-model="subjectsForm.subjectName"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-model="subjectsForm.isFrontDisplay"
          >
          </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <!-- 底部区域 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" @click="submitAddForm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  props: {
    // 父组件传递的学科名称
    correctSubjects: {
      type: Object,
      required: false
    }
  },
  created() {
    if (this.correctSubjects) {
      this.subjectsForm.subjectName = this.correctSubjects.subjectName
      this.subjectsForm.isFrontDisplay = !!this.correctSubjects.isFrontDisplay
      this.subjectsForm.id = this.correctSubjects.id
    }
  },
  data() {
    return {
      subjectsForm: {
        subjectName: '',
        isFrontDisplay: true, // 是否显示,默认是显示
        id: ''
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 提交表单数据并刷新数据列表
    submitAddForm() {
      this.$refs.subjectsForm.validate(async valid => {
        // 如果获取到的表单数据有效
        if (valid) {
          // 成功
          try {
            // 如果传递的值是存在的
            if (this.correctSubjects) {
              await update(this.subjectsForm)
              this.$emit('updateSubjects')
              this.$message.success('修改数据成功')
            } else {
              // console.log(11);
              await add(this.subjectsForm)
              this.$emit('addSubjects')
              this.$message.success('添加数据成功')
            }
            // 触发获取数据事件
          } catch (error) {
            this.$message.error('获取数据失败')
          }
          this.$emit('close')
        }
      })
    },
    // 如果用户取消数据提交，将输入框清空
    cancelSubmit() {
      this.$refs.subjectsForm.resetFields()
      this.subjectsForm.isFrontDisplay = true
      this.$emit('close')
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.subjects-add {
  .header {
    display: flex;
    flex-direction: column;
  }
}
.dialog-footer {
  text-align: right;
}
</style>
